package com.cilico.single.view;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Timer;

import android.view.View;

import com.cilico.single.ConfigManager;
import com.cilico.single.Mid;
import com.cilico.single.R;
import com.cilico.single.components.AtomParser;
import com.cilico.single.components.ChannelRepository;
import com.cilico.single.components.POI;
import com.cilico.single.components.PoiRepository;
import com.cilico.single.components.WaitDialog;
import com.cilico.single.components.mTextField;
import com.cilico.single.utils.Constant;
import com.cilico.single.utils.ConstantRepository;
import com.cilico.single.utils.InputDB;
import com.cilico.single.utils.Utils;

/**
 * Form Action处理
 * @author lv.xiangan
 *
 */

public class ChannelEntity {
	BaseView activity_;
	private final String CHANGE_CHANNEL_TASK = "changeChannel";
	private Mid mid_;
	String[] recentQueries_;
	private boolean isComeFromMap_;
	private Timer changeChannelTimer_;
	private final String inputDB_ = "QUERY_CHANNEL_INPUT_DB";
	boolean islogin_ = false;

	public ChannelEntity(Mid mid) {
		mid_ = mid;
	}

	private void cancelTasker() {
		if (changeChannelTimer_ != null) {
			changeChannelTimer_.cancel();
			changeChannelTimer_ = null;
		}
	}


	public void gotoDetailViewFromMainView(final String channelID, BaseView activity, final int viewId, final String mainChannelId, final String mainChannelTitle) {
		activity_ = activity;
		final BaseView activityTemp = activity;
		Channel ch = mid_.channelRepo_.getChannelByShortCut(mainChannelId);
		// 保存未读消息
		if (null != ch){
			int showNew = ch.showNew_;
			ch.showNew_ = 0;
			if (showNew > 0){
				Mid.saveProperty_.put(ch.id(), ch.total_);
	            if(mid_.um_.loginStatus_!=null){
					if (!mid_.um_.loginStatus_.equals("0")) {// 已登�?
						String key = ch.id().concat("_visitor");
						Mid.saveProperty_.put(key,getNoLoginNewInfoCount(ch.title()));
					} else {
						getNoLoginNewInfoCount(ch.title());
					}                    	
	            }
				Utils.saveProperties();
			}
		}
		BaseView.mid_.poiRepo_.channel_ = null;
		
		// 请求下一页面
		BaseView.mid_.waitDialog_.addFgTask(activityTemp, new WaitDialog.Task(0) {
			
			public void run(WaitDialog dlg) throws Exception {
				ChannelRepository temp = initTopChannelRepository(this, BaseView.mid_.channelRepo_.getCurrentChannelID());
				if (temp != null)
					BaseView.mid_.topChannelRepo_ = temp;
			}

			public void onSuccess(WaitDialog dlg) {
				// 获取数据成功之后再将界面数据压栈
				mid_.pushDisplayable(viewId, mainChannelId, mainChannelTitle);
				if (channelID != null)
					BaseView.mid_.topChannelRepo_.setCurrentChannelID(channelID);
				else
					BaseView.mid_.topChannelRepo_.setCurrentChannelID(0);
				BaseView.mid_.gotoDetailView(activityTemp, true, false, 0, true);
				super.onSuccess(dlg);
			}

			public void onFailure(WaitDialog dlg) {
				BaseView.mid_.removeDisplayable();
				BaseView.mid_.pushDisplayable(Mid.MAIN_VIEW, null, Constant.MAIN_TITLE);
				BaseView.mid_.alert(activityTemp, getErrMsg(), true);
				super.onFailure(dlg);
			}
		}, false);
		BaseView.mid_.waitDialog_.setText(ConstantRepository.getWaitText(ConstantRepository.LOADING_DATA));
	}
	
	/**
	 * 握手后直接进入详情页�?
	 * @param channelID
	 * @param activity
	 * @param viewId
	 * @param mainChannelId
	 * @param mainChannelTitle
	 */
	public void gotoDetailViewFromClientHello(final String channelID, BaseView activity, final int viewId, final String mainChannelId, final String mainChannelTitle) {
		activity_ = activity;
		final BaseView activityTemp = activity;
		BaseView.mid_.poiRepo_.channel_ = null;
		// 请求下一页面
		BaseView.mid_.waitDialog_.addFgTask(activityTemp, new WaitDialog.Task(0) {
			
			public void run(WaitDialog dlg) throws Exception {
				ChannelRepository temp = new ChannelRepository(BaseView.mid_);
				temp.downloadChannelList(this, BaseView.mid_.channelRepo_.getCurrentChannelID());
				if (temp != null)
					BaseView.mid_.topChannelRepo_ = temp;
			}
			
			public void onSuccess(WaitDialog dlg) {
				if (channelID != null)
					BaseView.mid_.topChannelRepo_.setCurrentChannelID(channelID);
				else
					BaseView.mid_.topChannelRepo_.setCurrentChannelID(0);
				BaseView.mid_.gotoDetailView(activityTemp, true, false, 0, true);
				super.onSuccess(dlg);
			}
			
			public void onFailure(WaitDialog dlg) {
				BaseView.mid_.removeDisplayable();
				BaseView.mid_.pushDisplayable(Mid.MAIN_VIEW, null, Constant.MAIN_TITLE);
				BaseView.mid_.alert(activityTemp, getErrMsg(), true);
				super.onFailure(dlg);
			}
		}, false);
		BaseView.mid_.waitDialog_.setText(ConstantRepository.getWaitText(ConstantRepository.LOADING_DATA));
	}

	private int getNoLoginNewInfoCount(String title) {
		int count = 0;
		return count;
	}
	

	void changeChannel(BaseView activity, final int index, final Boolean bl1) {
		activity_ = activity;
		final DetailView activityTemp = (DetailView) activity;
		BaseView.mid_.waitDialog_.cancelAndRemoveTask(CHANGE_CHANNEL_TASK);
		cancelTasker();
		// 如果二级菜单界面只有�?��channel,就不显示改channel
		final int size = mid_.topChannelRepo_.getSize();
		if (size == 1) {
			activity.removeAll();
		}
		BaseView.mid_.waitDialog_.addFgTask(activityTemp, new WaitDialog.Task(CHANGE_CHANNEL_TASK, 0) {
			public void run(WaitDialog dlg) throws Exception {
				// Thread.sleep(1000);
				// It should delay a while to reaction the next key pressing.
				// mid_.ChannelEntity_.cleanClonePoiRepository();
				initBelowContent(activityTemp, BaseView.mid_.topChannelRepo_.getChannel(index), this, bl1);
			}

			public void onSuccess(WaitDialog dlg) {
				// replacePoiRepository();
				BaseView.mid_.topChannelRepo_.setCurrentChannelID(index);
				// mid_.waitDialog_.removePartScreenItem();
				activityTemp.isShowEntry_ = false;
				// init to false again.
				// BaseView.mid_.poiRepo_.removeAllActionPoi();
				// delete titleBar!!!
				// activityTemp.resetTitleBarText();
				activityTemp.resetDetailType(activityTemp);
				activityTemp.setShowDetail(null);
				if (null != BaseView.mid_ && null != BaseView.mid_.getCurrentPoiSelection(false, activityTemp) && null != BaseView.mid_.getCurrentPoiSelection(false, activityTemp).getCurrentPOI())
					BaseView.mid_.poiRepo_.pushActionPoi(BaseView.mid_.getCurrentPoiSelection(false, activityTemp).getCurrentPOI().poi_);
				// 将控件添加至界面并且设置中层管理框架对齐方式为靠�?
				Utils.addManagerAndSetTop(activityTemp);
				super.onSuccess(dlg);
			}

			public void onFailure(WaitDialog dlg) {
				// mid_.popDisplayable();
				// mid_.waitDialog_.removePartScreenItem();
				
//              二级菜单界面的detailType_为DetailView.CHANNEL_LIST，当点击二级菜单出现弹出框时				
//				如果resetDetailType：点击�?取消”或者手机返回键回到二级菜单界面再次点击二级菜单无响应的情况
//				如果特殊处理不resetDetailType：点击确认按钮则会出现跳转时无法解析空白页面的问题，此时的解决办法就是在
//				Alert中alertCommandAction(0)的if (activity_ instanceof DetailView)时调用resetDetailType，这样就可以
//				正常跳转解析页面
//				if(activityTemp.detailType_ != DetailView.CHANNEL_LIST){
//					activityTemp.resetDetailType(activityTemp);
//				}
				
				activityTemp.resetDetailType(activityTemp);
				BaseView.mid_.topChannelRepo_.setCurrentChannelID(index);
				BaseView.mid_.alert(activityTemp, getErrMsg(), Mid.DETAIL_VIEW, true);
				super.onFailure(dlg);
			}
		}, true);

		BaseView.mid_.waitDialog_.setText(ConstantRepository.getWaitText(ConstantRepository.LOADING_DATA));
	}

	void changeChannel(final String url, BaseView activity, final Boolean bl1) {
		activity_ = activity;
		final LoginView activityTemp = (LoginView) activity;
		BaseView.mid_.waitDialog_.cancelAndRemoveTask(CHANGE_CHANNEL_TASK);
		cancelTasker();
		
		BaseView.mid_.waitDialog_.addFgTask(activityTemp, new WaitDialog.Task(CHANGE_CHANNEL_TASK, 0) {
			
			public void run(WaitDialog dlg) throws Exception {
				PoiRepository poiRepo = BaseView.mid_.poiRepo_;
				poiRepo.setActivity(activityTemp);
				if (bl1){
					poiRepo.downloadChannelPOIs(activityTemp, url, this);
				}
			}

			public void onSuccess(WaitDialog dlg) {
				activityTemp.isShowEntry_ = false;
				activityTemp.resetDetailType();
				activityTemp.setShowDetail(null);
				if (activityTemp instanceof LoginView) {
					LoginView loginView = (LoginView) activityTemp;
					loginView.removeAll();
					loginView.populate((POI) BaseView.mid_.poiRepo_.peekActionPoi());
					Utils.addManagerAndSetTop(activityTemp);
				}
				super.onSuccess(dlg);
			}

			public void onFailure(WaitDialog dlg) {
				BaseView.mid_.alert(activityTemp, getErrMsg(), Mid.DETAIL_VIEW, true);
				super.onFailure(dlg);
			}
		}, true);
		BaseView.mid_.waitDialog_.setText(ConstantRepository.getWaitText(ConstantRepository.LOADING_DATA));
	}	
	
	void stepDownDetailView(final BaseView bv, Boolean bl1) {
		BaseView.mid_.channelEntity_.changeChannel(bv, bv.currentItem_, bl1);
	}

	void stepUpDetailView(final BaseView bv) {
		activity_ = bv;
		cancelTasker();
		mid_.waitDialog_.addFgTask(bv, new WaitDialog.Task(0) {
			int view = -1;
			String id = null;
			int pView = -1;
			String pId = null;

			public void run(WaitDialog dlg) throws Exception {
				String[] lastView = mid_.popDisplayable();
				if (lastView != null) {
					view = Integer.parseInt(lastView[0]);
					id = lastView[1];
				}
				String[] parentView = mid_.peekDisplayable();
				if (parentView != null) {
					pView = Integer.parseInt(parentView[0]);
					pId = parentView[1];
				} else {
					parentView = lastView;
					pView = view;
					pId = id;
				}
				if (pView == Mid.MAIN_VIEW && pId == null) { // It means that the parent view is the main view.
					if (mid_.channelRepo_.isInitDownloadRequired())
						mid_.channelRepo_.downloadChannelList(this, null);
				} else if (pView == Mid.DETAIL_VIEW) { // It means that the parent view is a colletion.
					ChannelRepository temp = mid_.belowChannelRepo_;
					mid_.belowChannelRepo_ = mid_.topChannelRepo_;
					mid_.topChannelRepo_ = temp;
					mid_.topChannelRepo_.reset();
					mid_.topChannelRepo_.downloadChannelList(this, pId);
					mid_.topChannelRepo_.setCurrentChannelID(id);
				}
			}

			public void onSuccess(WaitDialog dlg) {
				if (pView == Mid.MAIN_VIEW) {
					mid_.topChannelRepo_.reset();
					mid_.belowChannelRepo_.reset();
					mid_.gotoView(pView, null, bv);
				} else if (view == Mid.MAP_VIEW) {
					mid_.gotoMainView(bv, false);
				} else {
					mid_.gotoView(view, null, bv);
				}
				super.onSuccess(dlg);
			}

			public void onFailure(WaitDialog dlg) {
				mid_.alert(bv, getErrMsg(), true);
				if (view == Mid.MAP_VIEW) {
					mid_.gotoMainView(bv, false);
				}
				super.onFailure(dlg);
			}
		}, false);
		mid_.waitDialog_.setText(ConstantRepository.getWaitText(ConstantRepository.LOADING_DATA));
	}

	void updateBelowChannelList() {
		// final Channel ch = mid_.topChannelRepo_.getCurrentChannel();
		// if (ch == null) {
		// return;
		// }
		// mid_.waitDialog_.addFgTask(new WaitDialog.Task(0) {
		// public void run(WaitDialog dlg) throws Exception {
		// mid_.belowChannelRepo_.downloadChannelList(this, ch.id());
		// }
		// public void onSuccess(WaitDialog dlg) {
		// DetailView detailView = mid_.getDetailView();
		// mid_.canvas_.myCanvas_ = detailView;
		// mid_.display_.setCurrent(mid_.canvas_);
		// detailView.setShowDetail(null);
		// detailView.refresh();
		// }
		// public void onFailure(WaitDialog dlg) {
		// mid_.alert(getErrMsg(), true);
		// }
		// }, false);
		// mid_.waitDialog_.setText(ConstantRepository.getWaitText(ConstantRepository.LOADING_DATA));
	}

	void updateBelowPOIList() {
		mid_.waitDialog_.addFgTask(activity_, new WaitDialog.Task(0) {
			public void run(WaitDialog dlg) throws Exception {
				mid_.poiRepo_.poiXML_ = null;
				mid_.getCurrentPoiSelection(false, activity_).populate(mid_.poiRepo_);
				mid_.poiRepo_.doReloadPoisInChannel(mid_.waitDialog_, true, this, mid_.topChannelRepo_.getCurrentChannel(), false);
			}

			public void onSuccess(WaitDialog dlg) {
				DetailView detailView = mid_.getDetailView(activity_);
				detailView.setShowDetail(null);
				mid_.poiRepo_.pushActionPoi(mid_.parser_.getOnePOI());
				Utils.addManagerAndSetTop(activity_);
				super.onSuccess(dlg);
			}

			public void onFailure(WaitDialog dlg) {
				mid_.alert(activity_, getErrMsg(), true);
				super.onFailure(dlg);
			}
		}, false);
		mid_.waitDialog_.setText(ConstantRepository.getWaitText(ConstantRepository.LOADING_DATA));
	}

	void resetBelowPOIList(DisplayPoi displayPOI, BaseView bv) {
		if (mid_.poiRepo_.poiXML_ == null) {
			reLoadBelowPOIList(bv);
		} else {
			try {
				mid_.poiRepo_.parsePOIs(mid_.poiRepo_.channel_, mid_.poiRepo_.poiXML_);
			} catch (Exception ex) {
			}
			mid_.getCurrentPoiSelection(false, bv).populate(mid_.poiRepo_);
			mid_.getCurrentPoiSelection(false, bv).setCurrentDisplayIndex(displayPOI.getDisplayIndex());
			DetailView detailView = mid_.getDetailView(bv);

			detailView.setShowDetail(null);
			Utils.addManagerAndSetTop(detailView);
		}
	}

	private void reLoadBelowPOIList(final BaseView bv) {
		mid_.waitDialog_.addFgTask(bv, new WaitDialog.Task(0) {
			public void run(WaitDialog dlg) throws Exception {
				mid_.getCurrentPoiSelection(false, bv).populate(mid_.poiRepo_);
				mid_.poiRepo_.doReloadPoisInChannel(mid_.waitDialog_, true, this, mid_.topChannelRepo_.getCurrentChannel(), false);
			}

			public void onSuccess(WaitDialog dlg) {
				DetailView detailView = mid_.getDetailView(bv);

				detailView.setShowDetail(null);
				Utils.addManagerAndSetTop(detailView);
				super.onSuccess(dlg);
			}

			public void onFailure(WaitDialog dlg) {
				mid_.alert(bv, getErrMsg(), true);
				super.onFailure(dlg);
			}
		}, false);
		mid_.waitDialog_.setText(ConstantRepository.getWaitText(ConstantRepository.LOADING_DATA));
	}


	private ChannelRepository initTopChannelRepository(WaitDialog.Task task, String channelId) throws Exception {
		// Find the channel upon the top channal repository
		String chanID = null;
		String[] view = BaseView.mid_.peekDisplayable();
		String[] parentView = BaseView.mid_.peekDisplayable(1);
		ChannelRepository temp = new ChannelRepository(BaseView.mid_);
		if (parentView != null && parentView[1] == null) { // 当父view�?MainView.
			Channel ch = null;
			if (channelId != null)
				ch = BaseView.mid_.channelRepo_.getChannel(channelId);
			else
				ch = BaseView.mid_.channelRepo_.getCurrentChannel();
			if (ch == null) {
				return null;
			}
			if (!ch.isCollection_) {
				temp.reset();
				temp.currentCollection_ = temp.defaultCollection_;
				temp.currentCollection_.setChannelIndexRange(0, 1);
				temp.addChannel(ch);
				temp.indexChannels();
				temp.setCurrentChannel(ch);
			} else {
				chanID = ch.id();
				temp.downloadChannelList(task, chanID);
			}
		} else if (view != null) {
			chanID = view[1];
			if (!channelId.equals(view[1])) {
				chanID = channelId;
				BaseView.mid_.channelRepo_.setCurrentChannelID(chanID);
			}
			// Download the content of the channel
			temp.downloadChannelList(task, channelId);
		}
		return temp;
	}

	private void initBelowContent(BaseView activity, Channel ch, WaitDialog.Task task,  Boolean bl1) throws Exception {
		activity_ = activity;
		DetailView detailView = (DetailView) activity;
		if (ch == null) {
			return;
		}
		detailView.isShowQueryView_ = false;
		if (ch.isCollection_) {
			// It's a collection and we must download the channel list of it and go to channel list.
			BaseView.mid_.belowChannelRepo_.downloadChannelList(task, ch.id());
		} else {
			// It's JUST a channel and we can go to its poi list.
			PoiRepository poiRepo = BaseView.mid_.poiRepo_;
			poiRepo.setActivity(activity);
			if (ch.isQueryChannel()) { // It means that the channel is a query channel
				poiRepo.poiXML_ = null;
				poiRepo.channel_ = ch;
				BaseView.mid_.getCurrentPoiSelection(false, activity).populate(poiRepo);
				BaseView.mid_.getDetailView(activity).isShowQueryView_ = true;
			} else {
				if (poiRepo.channel_ == ch && poiRepo.poiXML_ != null) {
					poiRepo.parsePOIs(poiRepo.channel_, poiRepo.poiXML_);
					BaseView.mid_.getCurrentPoiSelection(false, activity).populate(poiRepo);
				} else {
					// clonePoiRepository();
					// poiRepo = mid_.lastValidPoiRepo_;
					poiRepo.poiXML_ = null;
					poiRepo.channel_ = ch;
					BaseView.mid_.getCurrentPoiSelection(true, activity).populate(poiRepo);
					poiRepo.doReloadPoisInChannel(BaseView.mid_.waitDialog_, true, task, ch, bl1);
				}
			}
		}
	}

	public void sendForm(final String host, final String body, final boolean isNoCancel, final BaseView bv, final boolean showMap) {
		final DetailView detailView = (DetailView) bv;
		BaseView.mid_.waitDialog_.addFgTask(detailView, new WaitDialog.Task(0) {

			public void run(WaitDialog dlg) throws Exception {
				//用户结束任务
				if (BaseView.mid_.waitDialog_.getDisplayTaskStatus()) return; 
				String reply = null;
				//  读取本地页面
				if (host.startsWith("local://")) {
					String fileName = host.substring(8);
					reply = Utils.getStringFormAsset(ConfigManager.currentView_, fileName);
				} else {
					reply = (String) BaseView.mid_.hm_.sendPostRequest(host, body, this, null, null);
				}
				String tempreply = reply;
				if (host.indexOf("/atompub_s/") == -1 && host.indexOf("/gdb_s/") == -1 && host.indexOf("/phone_s/") == -1){//点击收藏时如果返回报文DecryptWithSessionKey(reply)的话解析出错
					reply = tempreply;
				}
				islogin_ = false;
				Utils.printOutToConsole("###################  sendForm().reply : " + reply);
				//用户结束任务
				if (BaseView.mid_.waitDialog_.getDisplayTaskStatus()) return;
				if (reply.contains("<phone_identity")){
					//解析登录后回来的九宫格报文，这样从免登陆直接登录后就可以返回到登录后的宫�?
					mid_.parser_.setLoginResultProperty(AtomParser.parseLoginResult_, mid_.um_, mid_.channelRepo_, null);
					android.util.Xml.parse(reply, mid_.parser_);
					mid_.channelRepo_.downloadChannelListSuccess();
				}
				if (bv.isInCeAirCjrLxrDiv_) {
					mid_.poiRepo_.popActionPoi();
					bv.delContentStack();
				}
				if (null == BaseView.mid_.parser_)
					BaseView.mid_.parser_ = new AtomParser(BaseView.mid_);
				BaseView.mid_.parser_.setOnePOIProperty(AtomParser.parseOnePOI_, bv);
				//用户结束任务
				if (BaseView.mid_.waitDialog_.getDisplayTaskStatus()) return;
				android.util.Xml.parse(reply, BaseView.mid_.parser_);
				if (!reply.contains("<pois") && !showMap) {//如果返回的不是地图的相关数据
					//此处对报文中�?<div id='pushState' class='skip'/>"数据的做弹栈处理，条件是接收到的报文包含此字符串�?
					//并且栈顶的poi的desc_报文中也包含此字符串，那么将栈顶poi弹出，压入当前新poi
					Object ob = mid_.poiRepo_.peekActionPoi();
					if (ob instanceof String && "pop".equals(ob.toString())) {
						BaseView.mid_.poiRepo_.popActionPoi();
						BaseView.mid_.poiRepo_.popActionPoi();
						mid_.getCurrentPoiSelection(false, activity_).removeAllElements();
						mid_.getCurrentPoiSelection(false, activity_).addPOI(BaseView.mid_.parser_.getOnePOI());
					} else if (reply.contains("<div id='pushState' class='skip'/>")) {
						if (ob != null && ob instanceof POI && ((POI)ob).skip_) {
							BaseView.mid_.poiRepo_.popActionPoi();
						}
					} else if(reply.contains("<div id='pushState' class='skip1'/>")) {
						if (ob != null && ob instanceof POI && ((POI)ob).skip_1) {
							BaseView.mid_.poiRepo_.popActionPoi();
						}
					}
					BaseView.mid_.poiRepo_.pushActionPoi(BaseView.mid_.parser_.getOnePOI());
				}
			}

			public void onSuccess(WaitDialog dlg) {
				if (islogin_){
					islogin_ = false;
				} else{
					//用户结束任务
					if (BaseView.mid_.waitDialog_.getDisplayTaskStatus()) {
						mid_.poiRepo_.popActionPoi();
						return;
					}
					detailView.delContentStack();
					detailView.isRunChangeChannel_ = false;
					detailView.showTab_ = false;
					detailView.populate((POI) mid_.poiRepo_.peekActionPoi());
					Utils.addManagerAndSetTop(detailView);
				}
				super.onSuccess(dlg);
			}

			public void onFailure(WaitDialog dlg) {
				BaseView.mid_.alert(detailView, getErrMsg(), Mid.DETAIL_VIEW, true);
				super.onFailure(dlg);
			}
		}, false, isNoCancel);
		BaseView.mid_.waitDialog_.setText(ConstantRepository.getWaitText(ConstantRepository.SENDING_DATA));
	}

	void queryChannel(String history, BaseView bv) {
		Channel queryCh_ = BaseView.mid_.poiRepo_.channel_;
		queryCh_.resetPaging();
		if (history != null) {
			if (recentQueries_ != null) {
				for (int i = 0; i < recentQueries_.length; ++i) {
					if (recentQueries_[i].equals(history)) {
						queryCh_.setQueryFromHistory(i);
						break;
					}
				}
			}
			queryPoisInChannel(queryCh_, bv);
		} else {
			String nameIsBlank = mid_.getDetailView(bv).createQueryString(queryCh_);
			if (nameIsBlank != null) {
				mid_.alert(bv, nameIsBlank, false);
			} else {
				queryCh_.genQueryString();
				queryPoisInChannel(queryCh_, bv);
			}
		}
	}

	void queryPoisInChannel(final Channel ch, final BaseView bv) {
		// FIXME: it's possible that we have a channel, it requires parameter
		// but we do not
		// have any values set yet. Temporarily, this happens because when we
		// save a channel
		// we do not save its value set. Hence when we redo this query after the
		// app restarts,
		// we get here with a non-empty param set but an empty value set. Skip
		// this app when
		// this happens.
		final String qpar = ch.queryString_;
		if (ch.numParams() > 0 && (qpar == null || qpar.length() == 0)) {
			return;
		}

		mid_.waitDialog_.addFgTask(bv, new WaitDialog.Task(0) {
			public void run(WaitDialog dlg) throws Exception {
				mid_.poiRepo_.downloadPois(ch, this, false);
			}

			public void onSuccess(WaitDialog dlg) {
				// 此处原有弹栈操作，鉴于已经去掉的前面的压棧操作，故注释掉
				// mid_.popDisplayable();
				ch.resetPaging();
				DetailView detailView = mid_.getDetailView(bv);
				detailView.isShowQueryView_ = false;
				detailView.detailType_ = DetailView.POI_LIST;
				detailView.setShowDetail(null);
				// 将控件添加至界面并且设置中层管理框架对齐方式为靠�?
				Utils.addManagerAndSetTop(detailView);
				super.onSuccess(dlg);
			}

			public void onFailure(WaitDialog dlg) {
				String str = getErrMsg();
				if (str.trim().equals(activity_.getString(R.string.noContent))) {
					mid_.alert(bv, str, false);
				} else {
					mid_.alert(bv, str, true);
				}
				super.onFailure(dlg);
			}
		}, false);
		mid_.waitDialog_.setText(ConstantRepository.getWaitText(ConstantRepository.LOADING_DATA));

	}

	/**
	 * Download a feed of content items.
	 */
	final void loadContentEntry(final POI poi, final BaseView bv) {
		final DetailView detailView = (DetailView) bv;
		mid_.waitDialog_.addFgTask(bv, new WaitDialog.Task(0) {
			String reply;
			int parentPage = 1;

			public void run(WaitDialog dlg) throws Exception {
				parentPage = mid_.poiRepo_.channel_.paging_.currentPage_;
				String url = mid_.poiRepo_.entryUrl_ + "&p=" + mid_.poiRepo_.channel_.paging_.downloadPage_;
				reply = mid_.hm_.sendRequest(url, this);
				mid_.poiRepo_.parsePOIs(mid_.poiRepo_.channel_, reply);
			}

			public void onSuccess(WaitDialog dlg) {
				mid_.poiRepo_.showEntryXml_ = reply;
				mid_.poiListSelection_.bv_.currentItem_ = 0;
				mid_.getCurrentPoiSelection(false, bv).populate(mid_.poiRepo_);
				if (!detailView.isShowEntry_) {
					mid_.poiRepo_.showEntryParent_ = poi;
					mid_.poiRepo_.showEntryParentPage_ = parentPage;
				}
				detailView.detailType_ = DetailView.POI_LIST;
				detailView.isShowEntry_ = true;
				detailView.setShowDetail(null);
				Utils.addManagerAndSetTop(detailView);
				super.onSuccess(dlg);
			}

			public void onFailure(WaitDialog dlg) {
				mid_.alert(detailView, getErrMsg(), Mid.DETAIL_VIEW, true);
				super.onFailure(dlg);
			}
		}, false);
		mid_.waitDialog_.setText(ConstantRepository.getWaitText(ConstantRepository.LOADING_DATA));
	}

	/**
	 * Download link content, link start with "lp:".
	 */
	final void loadLinkContent(final String url, final BaseView bv) {
		final DetailView detailView = (DetailView) bv;
		mid_.waitDialog_.addFgTask(detailView, new WaitDialog.Task(0) {
			public void run(WaitDialog dlg) throws Exception {
				String reply = mid_.hm_.sendRequest(url, this);
				if (null == BaseView.mid_.parser_)
					BaseView.mid_.parser_ = new AtomParser(BaseView.mid_);
				BaseView.mid_.parser_.setOnePOIProperty(AtomParser.parseOnePOI_, bv);
				android.util.Xml.parse(reply, BaseView.mid_.parser_);

				mid_.poiRepo_.pushActionPoi(mid_.parser_.getOnePOI());
			}

			public void onSuccess(WaitDialog dlg) {
				detailView.delContentStack();
				detailView.populate((POI) mid_.poiRepo_.popActionPoi());
				super.onSuccess(dlg);
			}

			public void onFailure(WaitDialog dlg) {
				mid_.alert(detailView, getErrMsg(), Mid.DETAIL_VIEW, true);
				super.onFailure(dlg);
			}
		}, false);
		mid_.waitDialog_.setText(ConstantRepository.getWaitText(ConstantRepository.SENDING_DATA));
	}

	final void loadLinkContentLogin(final String url, final String body, final BaseView bv) {
		activity_ = bv;
		final LoginView loginView = (LoginView) bv;
		mid_.waitDialog_.addFgTask(loginView, new WaitDialog.Task(0) {
			public void run(WaitDialog dlg) throws Exception {
				String reply = (String) mid_.hm_.sendPostRequest(url, body, this, null, null);
				Utils.printOutToConsole("###################  loadLinkContent().reply : " + reply);
				if (null == BaseView.mid_.parser_)
					BaseView.mid_.parser_ = new AtomParser(BaseView.mid_);
				BaseView.mid_.parser_.setOnePOIProperty(AtomParser.parseOnePOI_, bv);
				android.util.Xml.parse(reply, BaseView.mid_.parser_);
				mid_.poiRepo_.pushActionPoi(BaseView.mid_.parser_.getOnePOI());
			}

			public void onSuccess(WaitDialog dlg) {
				loginView.delContentStack();
				loginView.showTab_ = false;
				loginView.populate((POI) mid_.poiRepo_.peekActionPoi());
				loginView.addTitleBar();
				loginView.setLeftMenuMode(BaseView.BACK_MENU);
				if (null != BaseView.leftMenuText_) {
					loginView.titleBar_.showBack_ = true;
					loginView.titleBar_.backText_ = BaseView.leftMenuText_;
				}
				Utils.addManagerAndSetTop(loginView);
				super.onSuccess(dlg);
			}

			public void onFailure(WaitDialog dlg) {
				mid_.alert(loginView, getErrMsg(), Mid.DETAIL_VIEW, true);
				super.onFailure(dlg);
			}
		}, false);
		mid_.waitDialog_.setText(ConstantRepository.getWaitText(ConstantRepository.SENDING_DATA));
	}

	final void loadLinkContent(final String url, final String body, final BaseView bv) {
		activity_ = bv;
		final DetailView detailView = (DetailView) bv;
		mid_.waitDialog_.addFgTask(detailView, new WaitDialog.Task(0) {
			public void run(WaitDialog dlg) throws Exception {
				String reply = (String) mid_.hm_.sendPostRequest(url, body, this, null, null);
				if (null == BaseView.mid_.parser_)
					BaseView.mid_.parser_ = new AtomParser(BaseView.mid_);

				BaseView.mid_.parser_.setOnePOIProperty(AtomParser.parseOnePOI_, bv);
				android.util.Xml.parse(reply, BaseView.mid_.parser_);
				if (reply.contains("<div id='pushState' class='skip'/>")) {
					Object ob = mid_.poiRepo_.peekActionPoi();
					if (ob != null && ob instanceof POI && ((POI)ob).skip_) {
						BaseView.mid_.poiRepo_.popActionPoi();
					}
				} else if (reply.contains("<div id='pushState' class='skip1'/>")) {
					Object ob = mid_.poiRepo_.peekActionPoi();
					if (ob != null && ob instanceof POI && ((POI)ob).skip_1) {
						BaseView.mid_.poiRepo_.popActionPoi();
					}
				}
				mid_.poiRepo_.pushActionPoi(BaseView.mid_.parser_.getOnePOI());
			}

			public void onSuccess(WaitDialog dlg) {
				detailView.delContentStack();
				detailView.showTab_ = false;
				detailView.populate((POI) mid_.poiRepo_.peekActionPoi());
				Utils.addManagerAndSetTop(detailView);
				super.onSuccess(dlg);
			}

			public void onFailure(WaitDialog dlg) {
				mid_.alert(detailView, getErrMsg(), Mid.DETAIL_VIEW, true);
				super.onFailure(dlg);
			}
		}, false);
		mid_.waitDialog_.setText(ConstantRepository.getWaitText(ConstantRepository.SENDING_DATA));
	}

	final void loadLinkContentUpdate(final String url, final String body, final BaseView bv) {
		activity_ = bv;
		final DetailView detailView = (DetailView) bv;
		mid_.waitDialog_.addFgTask(detailView, new WaitDialog.Task(0) {
			public void run(WaitDialog dlg) throws Exception {
				String reply = (String) mid_.hm_.sendPostRequest(url, body, this, null, null);
				if (null == BaseView.mid_.parser_)
					BaseView.mid_.parser_ = new AtomParser(BaseView.mid_);

				BaseView.mid_.parser_.setOnePOIProperty(AtomParser.parseOnePOI_, bv);
				android.util.Xml.parse(reply, BaseView.mid_.parser_);
				mid_.poiRepo_.pushActionPoi(BaseView.mid_.parser_.getOnePOI());
			}

			public void onSuccess(WaitDialog dlg) {
				Utils.parseUsingkXML(((POI) mid_.poiRepo_.popActionPoi()).desc_, detailView);
				WaitDialog.Task.cancelProgressBar(bv);
				super.onSuccess(dlg);
			}

			public void onFailure(WaitDialog dlg) {
				mid_.alert(detailView, getErrMsg(), Mid.DETAIL_VIEW, true);
				super.onFailure(dlg);
			}
		}, false);
		mid_.waitDialog_.setText(ConstantRepository.getWaitText(ConstantRepository.SENDING_DATA));
	}
	
	public final void loadUpdateTable(final String url, final String body, final BaseView bv) {
		activity_ = bv;
		if (bv instanceof DetailView){
			final DetailView detailView = (DetailView) bv;
			mid_.waitDialog_.addBgTask( new WaitDialog.Task(0) {
				public void run(WaitDialog dlg) throws Exception {
					String reply = (String) mid_.hm_.sendPostRequest(url, body, this, null, null);
					if (!BaseView.ttimerIscannel_) {
						if (null == BaseView.mid_.parser_)
							BaseView.mid_.parser_ = new AtomParser(BaseView.mid_);
		
						BaseView.mid_.parser_.setOnePOIProperty(AtomParser.parseOnePOI_, bv);
						android.util.Xml.parse(reply, BaseView.mid_.parser_);
						mid_.poiRepo_.pushActionPoi(BaseView.mid_.parser_.getOnePOI());
					} else {
						mid_.poiRepo_.pushActionPoi("over");
					}
				}

				public void onSuccess(WaitDialog dlg) {
					Object ob = mid_.poiRepo_.popActionPoi();
					if (null != ob && ob instanceof POI && !BaseView.ttimerIscannel_) {
						String xmlStr = ((POI)ob).desc_.concat("<div updateTable='true'/>");
						Utils.parseUsingkXML(xmlStr, detailView);
					} else {
						BaseView.timerIsRunning_ = false;
					}
					super.onSuccess(dlg);
				}

				public void onFailure(WaitDialog dlg) {
					Object ob = mid_.poiRepo_.peekActionPoi();
					if (null != ob && ob instanceof String && "over".equals((String)ob)) {
						mid_.poiRepo_.popActionPoi();
					}
					BaseView.timerIsRunning_ = false;
					super.onFailure(dlg);
				}
			});
		} else if (bv instanceof LoginView){
			final LoginView lpLoginView = (LoginView) bv;
			mid_.waitDialog_.addBgTask( new WaitDialog.Task(0) {
				public void run(WaitDialog dlg) throws Exception {
					String reply = (String) mid_.hm_.sendPostRequest(url, body, this, null, null);
					if (!BaseView.ttimerIscannel_) {
						if (null == BaseView.mid_.parser_)
							BaseView.mid_.parser_ = new AtomParser(BaseView.mid_);
		
						BaseView.mid_.parser_.setOnePOIProperty(AtomParser.parseOnePOI_, bv);
						android.util.Xml.parse(reply, BaseView.mid_.parser_);
						mid_.poiRepo_.pushActionPoi(BaseView.mid_.parser_.getOnePOI());
					} else {
						mid_.poiRepo_.pushActionPoi("over");
					}
				}

				public void onSuccess(WaitDialog dlg) {
					Object ob = mid_.poiRepo_.popActionPoi();
					if (null != ob && ob instanceof POI && !BaseView.ttimerIscannel_) {
						String xmlStr = ((POI)ob).desc_.concat("<div updateTable='true'/>");
						Utils.parseUsingkXML(xmlStr, lpLoginView);
					} else {
						BaseView.timerIsRunning_ = false;
					}
					super.onSuccess(dlg);
				}

				public void onFailure(WaitDialog dlg) {
					Object ob = mid_.poiRepo_.peekActionPoi();
					if (null != ob && ob instanceof String && "over".equals((String)ob)) {
						mid_.poiRepo_.popActionPoi();
					}
					BaseView.timerIsRunning_ = false;
					super.onFailure(dlg);
				}
			});
		}

	}

	/**
	 * str: channel id or channel shortcut.
	 */
	void switchChannel(final BaseView bv, final String str, final boolean isShortCut, final String url,
			final String body, final boolean isNoCancel) {
		if (str == null || url == null)
			return;
		final DetailView detailView = (DetailView) bv;
		mid_.waitDialog_.addFgTask(bv, new WaitDialog.Task(0) {
			public void run(WaitDialog dlg) throws Exception {
				String xml = null;
				if (body == null)
					xml = mid_.hm_.sendRequest(url, this);
				else
					xml = (String) mid_.hm_.sendPostRequest(url, body, this, null, null);
				if (null == BaseView.mid_.parser_)
					BaseView.mid_.parser_ = new AtomParser(BaseView.mid_);

				BaseView.mid_.parser_.setOnePOIProperty(AtomParser.parseOnePOI_, bv);
				android.util.Xml.parse(xml, BaseView.mid_.parser_);
				mid_.poiRepo_.pushActionPoi(mid_.parser_.getOnePOI());
			}

			public void onSuccess(WaitDialog dlg) {
				detailView.delContentStack();
				detailView.populate((POI) mid_.poiRepo_.popActionPoi());
				Utils.addManagerAndSetTop(detailView);
				super.onSuccess(dlg);
			}

			public void onFailure(WaitDialog dlg) {
				mid_.alert(bv, getErrMsg(), Mid.DETAIL_VIEW, true);
				super.onFailure(dlg);
			}
		}, false, isNoCancel);
		mid_.waitDialog_.setText(ConstantRepository.getWaitText(ConstantRepository.LOADING_DATA));

	}

	boolean isComeFromMap() {
		return isComeFromMap_;
	}

	void setComeFromMap(boolean b) {
		isComeFromMap_ = b;
	}


	boolean isCurrentQueryChannel() {
		boolean isQueryChannel = false;
		try {
			if (mid_.topChannelRepo_.getCurrentChannel().isQueryChannel())
				isQueryChannel = true;
		} catch (Exception ex) {
		}
		return isQueryChannel;
	}

	/**
	 * backfill the data stored in the RMS to the components.
	 */
	void backfill(BaseView bv) {
		try {
			// Get data from RMS.
			Hashtable<String, String> ht = getInputRecord(bv, BaseView.mid_.topChannelRepo_.getCurrentChannelID());
			if (ht == null) {
				return;
			}
			// fill the components.
			mTextField textField;
			View view;
			int size = bv.tabBar_.getContentChildCount();
			for (int i = 0; i < size; i++) {
				try {
					view = (View) bv.tabBar_.getContentChild(i);
					if (view instanceof mTextField) {
						textField = (mTextField) view;
						textField.setText((String) ht.get(textField.attrName_));
					}
				} catch (Exception ex) {
					Utils.printException(ex);
				} finally {
					textField = null;
				}
			}
		} catch (Exception ex) {
			Utils.printException(ex);
		}
	}

	/**
	 * save the input text into RMS.
	 */
	void saveInput(BaseView bv) {
		StringBuffer sb = null;
		ArrayList<View> cmps = new ArrayList<View>();
		BaseView.traversingComponents(bv.tabBar_.getContentLayout(), cmps);
		sb = new StringBuffer();
		for (View vElement : cmps) {
			try {
				mTextField txtField = null;
				if (vElement instanceof mTextField) {
					txtField = (mTextField) vElement;
					sb.append("," + txtField.attrName_ + "," + txtField.getText());
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				Utils.printException(e);
			}
		}
		try {
			saveInputRecord(bv, BaseView.mid_.topChannelRepo_.getCurrentChannelID(), sb.toString().substring(1));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Utils.printException(e);
		}
	}

	private Hashtable<String, String> getInputRecord(BaseView bv, String channelID) throws Exception {
		InputDB inputDB = new InputDB(bv, inputDB_);
		String record = inputDB.getRecord(channelID);
		Hashtable<String, String> ht = getHashtable(record);
		return ht;
	}

	private void saveInputRecord(BaseView bv, String channelID, String record) throws Exception {
		InputDB inputDB = new InputDB(bv, inputDB_);
		inputDB.restoreRecord(channelID, record);
	}

	private Hashtable<String, String> getHashtable(String record) throws Exception {
		Hashtable<String, String> ht = null;
		if (record == null) {
			return null;
		}
		String[] strArr = Utils.string2Array(record, ",");
		if (strArr.length == 0 || strArr.length % 2 != 0) {
			return null;
		}
		ht = new Hashtable<String, String>();
		for (int i = 0; i < strArr.length; i++) {
			ht.put(strArr[i], strArr[i + 1]);
			i++;
		}
		return ht;
	}

	/**
	 * 跳转到本地页�?
	 * @param url
	 * @param bv
	 */
	public void goToLocalPage(final String url, final BaseView bv) {
		activity_ = bv;
		final DetailView detailView = (DetailView) bv;
		mid_.waitDialog_.addFgTask(detailView, new WaitDialog.Task(0) {
			public void run(WaitDialog dlg) throws Exception {
				if (url.startsWith("local://")) {
					String fileName = url.substring(8);
					String reply = Utils.getStringFormAsset(ConfigManager.currentView_, fileName);
					if (null == BaseView.mid_.parser_)
						BaseView.mid_.parser_ = new AtomParser(BaseView.mid_);

					BaseView.mid_.parser_.setOnePOIProperty(AtomParser.parseOnePOI_, bv);
					android.util.Xml.parse(reply, BaseView.mid_.parser_);
					mid_.poiRepo_.pushActionPoi(BaseView.mid_.parser_.getOnePOI());
				}
			}

			public void onSuccess(WaitDialog dlg) {
				detailView.delContentStack();
				detailView.showTab_ = false;
				detailView.populate((POI) mid_.poiRepo_.peekActionPoi());
				Utils.addManagerAndSetTop(detailView);
				super.onSuccess(dlg);
			}

			public void onFailure(WaitDialog dlg) {
				mid_.alert(detailView, getErrMsg(), Mid.DETAIL_VIEW, true);
				super.onFailure(dlg);
			}
		}, false);
		mid_.waitDialog_.setText(ConstantRepository.getWaitText(ConstantRepository.SENDING_DATA));

	}
}
